package com.chat;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;
import javax.swing.ProgressMonitor;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.text.BadLocationException;

public class AcceptFileThread extends Thread  {
	private Socket fileSenderSocket = null;
	private Chat c = null;
	private String fileName;
	private long fileSize;
	private String userInfo;
	public AcceptFileThread(Socket socket,Chat frame,String fileName,long fileSize,String userInfo){
			this.fileSenderSocket = socket;
			this.c=frame;
			this.fileName=fileName;
			this.fileSize=fileSize;
			this.userInfo=userInfo;
	}
	
	@Override
	public void run() {
		
		DataInputStream getFromSender = null;
		DataOutputStream sendToSender = null;
		DataOutputStream fileOutput = null;
		FileOutputStream saveFileStream = null;
		ProgressMonitor progressMonitor = null;
		try {
			getFromSender = new DataInputStream(
					new BufferedInputStream(fileSenderSocket.getInputStream()));
			sendToSender = new DataOutputStream(
					new BufferedOutputStream(fileSenderSocket.getOutputStream()));

			int permit = JOptionPane.showConfirmDialog(c,
					"接受文件:" + fileName +"?", "文件传输请求：", JOptionPane.YES_NO_OPTION);
			if (permit == JOptionPane.YES_OPTION) {
				sendToSender.writeBytes("accepted\n");
				sendToSender.flush();

				JFileChooser destinationFileChooser = new JFileChooser(".");
				destinationFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int status = destinationFileChooser.showSaveDialog(c);

				File destinationPath = null;
				if (status == JFileChooser.APPROVE_OPTION) {
					destinationPath = new File(destinationFileChooser.getSelectedFile().getPath());

				}

				byte judge = getFromSender.readByte();
				if (judge > 0) {
					File savedFile = new File(destinationPath.getAbsolutePath() + "\\" + fileName);
					saveFileStream = new FileOutputStream(savedFile);
					fileOutput = new DataOutputStream(saveFileStream);
					ProgressMonitorInputStream monitor = new ProgressMonitorInputStream(c,
							"接受文件： " + fileName, getFromSender);

					progressMonitor = monitor.getProgressMonitor();
					progressMonitor.setMaximum((int) fileSize);

					int read_unit = 500;
					int readed = 0;
					float process = 0;

					while (true) {
						byte[] data = new byte[read_unit];
						int in = monitor.read(data);
						readed += in;
						process = (float) readed / fileSize * 100;
						progressMonitor.setNote(process + " % 完成");
						progressMonitor.setProgress(readed);
						if (in <= 0) {
							break;
						}
						fileOutput.write(data, 0, in);
					}

					fileOutput.flush();
					if (savedFile.length() < fileSize) {
						JOptionPane.showMessageDialog(c, "传输中断!", "错误", JOptionPane.ERROR_MESSAGE);
					}
					
					//本地聊天框显示
					c.getDoc().insertString(c.getDoc().getLength(), userInfo+"\n", c.getFontAttrib().getUserAttrSet());
					c.getDoc().insertString(c.getDoc().getLength(), "接受文件:" + fileName + "，大小为:" + fileSize
							+ "字节，保存地址:" + destinationPath + "\n", c.getFontAttrib().getDefaultAttrSet());

				} else {
					JOptionPane.showMessageDialog(c, "源文件没有找到!", "错误", JOptionPane.ERROR_MESSAGE);
				}

			} else if (permit == JOptionPane.NO_OPTION) {
				sendToSender.writeBytes("refused\n");
				sendToSender.flush();
			}
		} catch (IOException ex) {
			// JOptionPane.showMessageDialog(frame, "传输中断!",
			// "错误", JOptionPane.ERROR_MESSAGE);
			System.out.println("00000000000000");
			ex.printStackTrace();
		} catch (BadLocationException e) {
			e.printStackTrace();
		} finally {
			try {
				getFromSender.close();
				sendToSender.close();
				if (fileOutput != null) {
					fileOutput.close();
				}
				if (saveFileStream != null) {
					saveFileStream.close();
				}
				if (progressMonitor != null) {
					progressMonitor.close();
				}

				fileSenderSocket.close();
			} catch (IOException e) {
			}
		}
	}
}
